using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SyncUdp.Utility
{
    using SyncUdp.Event;
    using SyncUdp.Interface;
    using System;
    using System.IO;

    public interface INetworkLogUtility
    {
        /// <summary>
        /// 日志文件的路径
        /// </summary>
        public string LogFilePath { get; }

        /// <summary>
        /// 将消息载入日志
        /// </summary>
        /// <param name="msg"></param>
        public void Logging(string msg);

        public void Close();
    }

    /// <summary>
    /// 网络日志工具
    /// </summary>
    public class NetworkLogUtility : INetworkLogUtility
    {
        /// <summary>
        /// 日志文件路径
        /// </summary>
        string _logFilePath;

        /// <summary>
        /// 流写入器
        /// </summary>
        StreamWriter _writer;

        public NetworkLogUtility(string fileName)
        {
            // 日志文件内容精确至秒
            var logPath = Application.dataPath + @"\NetworkLogs";
            var date = DateTime.Today.ToString("yyyy-MM-dd");
            _logFilePath = Path.Combine(logPath, $"{fileName} {date}.txt");
            // 判断文件夹是否存在
            if (Directory.Exists(logPath) == false)
                Directory.CreateDirectory(logPath);
            FileStream fileStream = null;
            // 判断日志文件是否存在
            // 不存在就创建，存在则写入消息
            if (File.Exists(_logFilePath))
                fileStream = new FileStream(_logFilePath, FileMode.Append);
            else
                fileStream = new FileStream(_logFilePath, FileMode.CreateNew);
            _writer = new StreamWriter(fileStream);
        }

        #region 方法实现
        public string LogFilePath => _logFilePath;

        public void Logging(string msg)
        {
            _writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            _writer.WriteLine(msg);
        }

        public void Close()
        {
            _writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            _writer.WriteLine("NetworkLog：关闭通信..." + Environment.NewLine);
            _writer.Close();
        }
        #endregion
    }
}
